﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DriveBeamEditor.Interfaces;

namespace DriveBeamEditor.Controls.General
{
    public partial class PathButton : XButton
    {
        #region Fields

        private string _initialDirectory;
        private string _dialogDescription;
        private IEditor _editorControl;

        #endregion

        #region Properties

        public string InitialDirectory
        {
            get { return _initialDirectory; }
            set
            {
                if (_initialDirectory == value) return;
                _initialDirectory = value;
            }
        }

        public string DialogDescription
        {
            get { return _dialogDescription; }
            set
            {
                if (_dialogDescription == value) return;
                _dialogDescription = value;
            }
        }

        public IEditor EditorControl
        {
            get { return _editorControl; }
            set
            {
                if (_editorControl == value) return;
                var oldValue = _editorControl != null && _editorControl.EditValue != null ? _editorControl.EditValue.ToString() : null;
                _editorControl = value;
                if (oldValue != null)
                    _editorControl.EditValue = oldValue;
            }
        }

        #endregion

        #region CTORs

        public PathButton()
        {
            InitializeComponent();
            InitializePathStuff();
        }

        #endregion

        #region Overrides

        protected override void OnTextChanged(EventArgs e)
        {
            if (!Text.Equals("..."))
            {
                Text = "...";
                return;
            }
            base.OnTextChanged(e);
        }

        #endregion

        #region Methods

        private void InitializePathStuff()
        {
            Size = new Size(33, 20);
            Text = "...";
            Click += (s, e) =>
            {
                using (var dialog = new FolderBrowserDialog())
                {
                    dialog.ShowNewFolderButton = false;
                    dialog.Description = ((PathButton)s).DialogDescription;
                    if (Directory.Exists(((PathButton)s).InitialDirectory))
                        dialog.SelectedPath = ((PathButton)s).InitialDirectory;

                    if (dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK && EditorControl != null)
                    {
                        EditorControl.EditValue = dialog.SelectedPath;
                    }
                }
            };
        }

        #endregion
    }
}
